package com.example.qihuibao.widget.view

import android.app.TimePickerDialog
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.qihuibao.R
import com.example.qihuibao.bean.*
import com.example.qihuibao.constant.Global
import com.example.qihuibao.enum.MealStatus
import com.example.qihuibao.enum.OrderMode
import com.example.qihuibao.enum.Status
import com.example.qihuibao.module.main.MainActivity
import com.example.qihuibao.utils.EnumUtils
import com.example.qihuibao.utils.extension.toast

/**
 *     author : cwwei
 *     e-mail : 494545699@qq.com
 *     date   : 2022/08/13
 *     desc   :
 */
class MealInfoLayout(ctx:Context, MealID:String) : FrameLayout(ctx) {
    private lateinit var activity: MainActivity
    private lateinit var root: View
    private var modify = false
    private val mealSetList = mutableListOf<MealSet>()
    private lateinit var rv_employ: CommonRecyclerView
    private var MealID = "01"
    private var selectStat: MealStatus? = null
    private var selectOrderMode: OrderMode? = null
    private var rspQueryMealInfoBean: RspQueryMealInfoBean? = null
    private var feeId = ""
    private var feeName = ""

    init {
        if (ctx is MainActivity) {
            activity = ctx
            this.MealID = MealID
        }
        root = LayoutInflater.from(ctx).inflate(R.layout.layout_meal, this, true)
        root.setOnClickListener {  }//禁止点击事件穿透
        initView()
    }

    private fun initView() {
        root.findViewById<TextView>(R.id.tv_title).text = "餐别${MealID}信息"
        root.findViewById<View>(R.id.iv_back).setOnClickListener { (parent as ViewGroup).removeView(this) }
        root.findViewById<View>(R.id.iv_add_mealset).setOnClickListener { addMealSet() }
        root.findViewById<View>(R.id.tv_update).setOnClickListener { update() }
        queryMealInfo()
    }

    private fun queryMealInfo() {
        activity.getMainViewModel().queryMealInfo(ReqQueryMealInfoBean(CantID = Global.canteenId, MealID)).observe(activity) {
            if (it.RetCode == "0") {
                rspQueryMealInfoBean = it
                root.findViewById<EdittextWithText>(R.id.et_MealID).setContentWithModify("${it.MealID}") {text ->
                    rspQueryMealInfoBean?.MealID = text
                }
                root.findViewById<EdittextWithText>(R.id.et_MealName).setContentWithModify("${it.MealName}") {text ->
                    rspQueryMealInfoBean?.MealName = text
                }
                val stats = EnumUtils.getMealStatus(it.Status?:"0")
                selectStat = stats[0]
                val spStatus = root.findViewById<Spinner>(R.id.sp_Status)
                spStatus?.adapter = ArrayAdapter(activity, android.R.layout.simple_list_item_1, stats)
                spStatus?.onItemSelectedListener = object: AdapterView.OnItemSelectedListener {
                    override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                        selectStat = stats[position]
                    }

                    override fun onNothingSelected(parent: AdapterView<*>?) {}
                }
                root.findViewById<CheckBox>(R.id.cb_OrderFlag).isChecked = it.OrderFlag == "1"
                root.findViewById<CheckBox>(R.id.cb_SpotFlag).isChecked = it.SpotFlag == "1"
                root.findViewById<CheckBox>(R.id.cb_CancelFlag).isChecked = it.CancelFlag == "1"
                root.findViewById<CheckBox>(R.id.cb_WeekCalendar1).isChecked = EnumUtils.getEnable("${it.WeekCalendar}", 1)
                root.findViewById<CheckBox>(R.id.cb_WeekCalendar2).isChecked = EnumUtils.getEnable("${it.WeekCalendar}", 2)
                root.findViewById<CheckBox>(R.id.cb_WeekCalendar3).isChecked = EnumUtils.getEnable("${it.WeekCalendar}", 3)
                root.findViewById<CheckBox>(R.id.cb_WeekCalendar4).isChecked = EnumUtils.getEnable("${it.WeekCalendar}", 4)
                root.findViewById<CheckBox>(R.id.cb_WeekCalendar5).isChecked = EnumUtils.getEnable("${it.WeekCalendar}", 4)
                root.findViewById<CheckBox>(R.id.cb_WeekCalendar6).isChecked = EnumUtils.getEnable("${it.WeekCalendar}", 6)
                root.findViewById<CheckBox>(R.id.cb_WeekCalendar7).isChecked = EnumUtils.getEnable("${it.WeekCalendar}", 7)
                root.findViewById<TextViewWithText>(R.id.tv_UseBeginTime).setText("${if (it.UseBeginTime.isNullOrEmpty()) "点击选择" else it.UseBeginTime}") {
                    showTimePicker {time->
                        rspQueryMealInfoBean?.UseBeginTime = time
                        root.findViewById<TextViewWithText>(R.id.tv_UseBeginTime).setContent(time)
                    }
                }
                root.findViewById<TextViewWithText>(R.id.tv_UseEndTime).setText("${if (it.UseEndTime.isNullOrEmpty()) "点击选择" else it.UseEndTime}") {
                    showTimePicker {time->
                        rspQueryMealInfoBean?.UseEndTime = time
                        root.findViewById<TextViewWithText>(R.id.tv_UseEndTime).setContent(time)
                    }
                }
                root.findViewById<TextViewWithText>(R.id.tv_SpotUseBeginTime).setText("${if (it.SpotUseBeginTime.isNullOrEmpty()) "点击选择" else it.SpotUseBeginTime}") {
                    showTimePicker {time->
                        rspQueryMealInfoBean?.SpotUseBeginTime = time
                        root.findViewById<TextViewWithText>(R.id.tv_SpotUseBeginTime).setContent(time)
                    }
                }
                root.findViewById<TextViewWithText>(R.id.tv_SpotUseEndTime).setText("${if (it.SpotUseEndTime.isNullOrEmpty()) "点击选择" else it.SpotUseEndTime}") {
                    showTimePicker {time->
                        rspQueryMealInfoBean?.SpotUseEndTime = time
                        root.findViewById<TextViewWithText>(R.id.tv_SpotUseEndTime).setContent(time)
                    }
                }
                root.findViewById<EdittextWithText>(R.id.et_OrderDeadlineDate).setContentWithModify("${it.OrderDeadlineDate}") {text ->
                    rspQueryMealInfoBean?.OrderDeadlineDate = text
                }
                root.findViewById<TextViewWithText>(R.id.tv_OrderDeadlineTime).setText("${if (it.OrderDeadlineTime.isNullOrEmpty()) "点击选择" else it.OrderDeadlineTime}") {
                    showTimePicker {time->
                        rspQueryMealInfoBean?.OrderDeadlineTime = time
                        root.findViewById<TextViewWithText>(R.id.tv_OrderDeadlineTime).setContent(time)
                    }
                }
                root.findViewById<EdittextWithText>(R.id.et_CancelDeadlineDate).setContentWithModify("${it.CancelDeadlineDate}") {text ->
                    rspQueryMealInfoBean?.CancelDeadlineDate = text
                }
                root.findViewById<TextViewWithText>(R.id.tv_CancelDeadlineTime).setText("${if (it.CancelDeadlineTime.isNullOrEmpty()) "点击选择" else it.CancelDeadlineTime}") {
                    showTimePicker {time->
                        rspQueryMealInfoBean?.CancelDeadlineTime = time
                        root.findViewById<TextViewWithText>(R.id.tv_CancelDeadlineTime).setContent(time)
                    }
                }
                root.findViewById<EdittextWithText>(R.id.et_PerOrderLimit).setContentWithModify("${it.PerOrderLimit}") {text ->
                    rspQueryMealInfoBean?.PerOrderLimit = if (text.isEmpty()) 0 else text.toInt()
                }
                root.findViewById<EdittextWithText>(R.id.et_PerSpotLimit).setContentWithModify("${it.PerSpotLimit}") {text ->
                    rspQueryMealInfoBean?.PerSpotLimit = if (text.isEmpty()) 0 else text.toInt()
                }
                root.findViewById<EdittextWithText>(R.id.et_PerTotalLimit).setContentWithModify("${it.PerTotalLimit}") {text ->
                    rspQueryMealInfoBean?.PerTotalLimit = if (text.isEmpty()) 0 else text.toInt()
                }
                root.findViewById<EdittextWithText>(R.id.et_AllOrderLimit).setContentWithModify("${it.AllOrderLimit}") {text ->
                    rspQueryMealInfoBean?.AllOrderLimit = if (text.isEmpty()) 0 else text.toInt()
                }
                root.findViewById<EdittextWithText>(R.id.et_AllSpotLimit).setContentWithModify("${it.AllSpotLimit}") {text ->
                    rspQueryMealInfoBean?.AllSpotLimit = if (text.isEmpty()) 0 else text.toInt()
                }
                root.findViewById<EdittextWithText>(R.id.et_AllTotalLimit).setContentWithModify("${it.AllTotalLimit}") {text ->
                    rspQueryMealInfoBean?.AllTotalLimit = if (text.isEmpty()) 0 else text.toInt()
                }
                val orderModes = EnumUtils.getOrderMode(it.OrderMode?:"0")
                selectOrderMode = orderModes[0]
                val spOrderMode = root.findViewById<Spinner>(R.id.sp_OrderMode)
                spOrderMode?.adapter = ArrayAdapter(activity, android.R.layout.simple_list_item_1, orderModes)
                spOrderMode?.onItemSelectedListener = object: AdapterView.OnItemSelectedListener {
                    override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                        selectOrderMode = orderModes[position]
                    }

                    override fun onNothingSelected(parent: AdapterView<*>?) {}
                }
                root.findViewById<CheckBox>(R.id.cb_DeliverFlag).isChecked = it.DeliverFlag == "1"
                //
                if (!it.MealSetlList.isNullOrEmpty()) {
                    mealSetList.clear()
                    mealSetList.addAll(it.MealSetlList)
                }
                root.findViewById<CommonRecyclerView>(R.id.rv_MealSetlList).init(
                    R.layout.item_mealset3,
                    LinearLayoutManager(context, RecyclerView.VERTICAL, false),
                    mealSetList,
                    { parent, pos ->
                        if (mealSetList.isNotEmpty()) {
                            parent.findViewById<EdittextWithText>(R.id.et_MealSetID).setContentWithModify("${mealSetList[pos].MealSetID}") {text ->
                                mealSetList[pos].MealSetID = text
                            }
                            parent.findViewById<EdittextWithText>(R.id.et_MealSetName).setContentWithModify("${mealSetList[pos].MealSetName}") {text ->
                                mealSetList[pos].MealSetName = text
                            }
                            parent.findViewById<CheckBox>(R.id.cb_Status).isChecked = mealSetList[pos].Status == "1"
                            parent.findViewById<EdittextWithText>(R.id.et_PerOrderLimit).setContentWithModify("${mealSetList[pos].PerOrderLimit}") {text ->
                                mealSetList[pos].PerOrderLimit = if (text.isEmpty()) 0 else  text.toInt()
                            }
                            parent.findViewById<EdittextWithText>(R.id.et_PerSpotLimit).setContentWithModify("${mealSetList[pos].PerSpotLimit}") {text ->
                                mealSetList[pos].PerSpotLimit = if (text.isEmpty()) 0 else  text.toInt()
                            }
                            parent.findViewById<EdittextWithText>(R.id.et_PerTotalLimit).setContentWithModify("${mealSetList[pos].PerTotalLimit}") {text ->
                                mealSetList[pos].PerTotalLimit = if (text.isEmpty()) 0 else  text.toInt()
                            }
                            parent.findViewById<EdittextWithText>(R.id.et_AllOrderLimit).setContentWithModify("${mealSetList[pos].AllOrderLimit}") {text ->
                                mealSetList[pos].AllOrderLimit = if (text.isEmpty()) 0 else  text.toInt()
                            }
                            parent.findViewById<EdittextWithText>(R.id.et_AllSpotLimit).setContentWithModify("${mealSetList[pos].AllSpotLimit}") {text ->
                                mealSetList[pos].AllSpotLimit = if (text.isEmpty()) 0 else  text.toInt()
                            }
                            parent.findViewById<EdittextWithText>(R.id.et_AllTotalLimit).setContentWithModify("${mealSetList[pos].AllTotalLimit}") {text ->
                                mealSetList[pos].AllTotalLimit = if (text.isEmpty()) 0 else  text.toInt()
                            }
                            parent.findViewById<View>(R.id.iv_delete).setOnClickListener {
                                mealSetList.removeAt(pos)
                                root.findViewById<CommonRecyclerView>(R.id.rv_MealSetlList).adapter?.notifyDataSetChanged()
                            }
                        }
                    }
                )
                root.findViewById<CommonRecyclerView>(R.id.rv_FeeList).init(
                    R.layout.item_text,
                    LinearLayoutManager(context, RecyclerView.VERTICAL, false),
                    it.FeeList,
                    { parent, pos ->
                        (parent as TextView).text = "收费标准ID：${it.FeeList!![pos].FeeID}\n" +
                                "收费标准名称：${it.FeeList!![pos].FeeName}"
                    }
                )
            }else {
                activity?.toast("查询失败")
            }
        }
    }

    private fun showTimePicker(selected:(time:String)->Unit) {
        TimePickerDialog(activity, { view, hourOfDay, minute ->
            selected("${if (hourOfDay<10) "0$hourOfDay" else hourOfDay}:${if (minute<10) "0$minute" else minute}")
        }, 0, 0, true).show()
    }

    private fun addMealSet() {
        mealSetList.add(MealSet(
            MealSetID = "",
            MealSetName = "",
            Status = "0",
        ))
        root.findViewById<CommonRecyclerView>(R.id.rv_MealSetlList).adapter?.notifyDataSetChanged()
    }

    private fun updateFee() {
        if (feeId.isEmpty() || feeName.isEmpty()) {
            activity.toast("输入有误")
            return
        }
        val req = ReqUpdateFeesBean()
        activity.getMainViewModel().updateFees(req).observe(activity) {
            activity.toast("${if (it.RetCode == "0") "更新成功" else "更新失败：${it.RetMsg}"}")
            if (it.RetCode == "0") {
                queryMealInfo()
            }
        }
    }

    private fun update() {
        val req = ReqUpdateMealInfoBean(
            CantID	= Global.canteenId,
            MealID	= "${rspQueryMealInfoBean?.MealID}",
            MealName	= "${rspQueryMealInfoBean?.MealName}",
            Status	= "${selectStat?.value}",
            OrderFlag	= if (root.findViewById<CheckBox>(R.id.cb_OrderFlag).isChecked) "1" else "0",
            SpotFlag	= if (root.findViewById<CheckBox>(R.id.cb_SpotFlag).isChecked) "1" else "0",
            CancelFlag	= if (root.findViewById<CheckBox>(R.id.cb_CancelFlag).isChecked) "1" else "0",
            WeekCalendar	= "${if (root.findViewById<CheckBox>(R.id.cb_WeekCalendar1).isChecked) "1" else "0"}${if (root.findViewById<CheckBox>(R.id.cb_WeekCalendar2).isChecked) "1" else "0"}${if (root.findViewById<CheckBox>(R.id.cb_WeekCalendar3).isChecked) "1" else "0"}${if (root.findViewById<CheckBox>(R.id.cb_WeekCalendar4).isChecked) "1" else "0"}${if (root.findViewById<CheckBox>(R.id.cb_WeekCalendar5).isChecked) "1" else "0"}${if (root.findViewById<CheckBox>(R.id.cb_WeekCalendar6).isChecked) "1" else "0"}${if (root.findViewById<CheckBox>(R.id.cb_WeekCalendar7).isChecked) "1" else "0"}",
            UseBeginTime	= "${rspQueryMealInfoBean?.UseBeginTime}",
            UseEndTime	= "${rspQueryMealInfoBean?.UseEndTime}",
            SpotUseBeginTime	= "${rspQueryMealInfoBean?.SpotUseBeginTime}",
            SpotUseEndTime	= "${rspQueryMealInfoBean?.SpotUseEndTime}",
            OrderDeadlineDate	= "${rspQueryMealInfoBean?.OrderDeadlineDate}",
            OrderDeadlineTime	= "${rspQueryMealInfoBean?.OrderDeadlineTime}",
            CancelDeadlineDate	= "${rspQueryMealInfoBean?.CancelDeadlineDate}",
            CancelDeadlineTime	= "${rspQueryMealInfoBean?.CancelDeadlineTime}",
            PerOrderLimit	= rspQueryMealInfoBean?.PerOrderLimit?:0,
            PerSpotLimit	= rspQueryMealInfoBean?.PerSpotLimit?:0,
            PerTotalLimit	= rspQueryMealInfoBean?.PerTotalLimit?:0,
            AllOrderLimit	= rspQueryMealInfoBean?.AllOrderLimit?:0,
            AllSpotLimit	= rspQueryMealInfoBean?.AllSpotLimit?:0,
            AllTotalLimit	= rspQueryMealInfoBean?.AllTotalLimit?:0,
            MealSetList = mealSetList
        )
        activity.getMainViewModel().updateMealInfo(req).observe(activity) {
            activity.toast("${if (it.RetCode == "0") "更新成功" else "更新失败：${it.RetMsg}"}")
            if (it.RetCode == "0") {
                queryMealInfo()
            }
        }
    }
}